package com.bucks.service;

import com.bucks.entity.Coffee;
import com.bucks.entity.CoffeeOrder;
import com.bucks.entity.OrderState;
import com.bucks.repository.CoffeeOrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**

 * @date 2019-11-14
 */
@Service
@Transactional
@Slf4j
public class CoffeeOrderService {
    @Autowired
    private CoffeeOrderRepository coffeeOrderRepository;

    public CoffeeOrder get(Long id){
        return coffeeOrderRepository.getOne(id);
    }

    public CoffeeOrder createOrder(String customer, Coffee...coffees){
        CoffeeOrder order = CoffeeOrder.builder()
                .customer(customer)
                .items(Arrays.asList(coffees))
                .state(OrderState.INIT)
                .build();
        CoffeeOrder saved = coffeeOrderRepository.save(order);
        log.info("New Order: {}" , saved);
        return saved;
    }

    public Boolean updateState(CoffeeOrder order,OrderState state){
        if (state.compareTo(order.getState())<=0){
            log.warn("Wrong state order: {} , {}" ,state,order.getState());
            return false;
        }
        order.setState(state);
        coffeeOrderRepository.save(order);
        log.info("Updated Order: {}",order);
        return true;
    }






}
